package main

import (
	"context"
	"github.com/gookit/color"
	"log"
	"net/http"
	"os"
	"os/signal"
	"seven-admin/core"
	"seven-admin/core/config"
	"seven-admin/helper"
	"seven-admin/route"
	"syscall"
	"time"
)

func main() {
	// MQTT
	//go gateway.InitMqtt()
	// helper
	go helper.Run()
	// 初始化DI
	route.InitDI()
	// 初始化router
	router := route.InitRouter()
	// 初始化server
	s := route.InitServer(router)

	// 创建一个通道来监听操作系统信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		// 打印服务信息
		color.Greenln("Server is running at port: ", config.Env.ServerPort)
		// 运行服务
		err := s.ListenAndServe()
		if err != nil {
			if err == http.ErrServerClosed {
				log.Println("Server closed under request")
			}
			return
		}
	}()

	<-quit
	log.Println("Server is shutting down...")

	// 优雅关闭服务
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := gracefulShutdown(s, ctx); err != nil {
		log.Fatalln("Server forced to shutdown:", err)
	}

	log.Println("Server exited")
}

func gracefulShutdown(s *http.Server, ctx context.Context) error {
	if err := s.Shutdown(ctx); err != nil {
		closeResources()
		return err
	}
	closeResources()
	return nil
}

func closeResources() {
	core.Logger.Sync()
	core.CloseDB()
	if influx := core.GetInfluxDB(); influx != nil {
		influx.Close()
	}
	//gateway.MqttClient.Disconnect(10)
	color.Greenln("Resources closed successfully!")
	os.Exit(0)
}
